import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/api/calendar.dart';
import 'package:geomancy/models/auspicious_day_list_model.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/utils.dart';
import 'package:geomancy/widgets/common_btn.dart';
import 'package:geomancy/widgets/common_header.dart';
import 'package:geomancy/widgets/common_list.dart';
import 'package:geomancy/widgets/common_loading_circle.dart';
import 'package:geomancy/widgets/common_text.dart';
import 'package:geomancy/widgets/common_title.dart';
import 'package:geomancy/widgets/custom_refresh_header.dart';
import 'package:geomancy/widgets/date_picker/index.dart';
import 'package:geomancy/widgets/stroke_text.dart';
import 'package:go_router/go_router.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class GoodDayResultPage extends StatefulWidget {
  final String type;
  final String status; // y j
  const GoodDayResultPage({super.key, required this.type, required this.status});

  @override
  State<GoodDayResultPage> createState() => _GoodDayResultPageState();
}

class _GoodDayResultPageState extends State<GoodDayResultPage> {
  final RefreshController _refreshController = RefreshController();
  int page = 1;
  int currentListLength = 0;
  int size = 10; //接口默认一次返回10条数据
  List<AuspiciousDayItemModel> dataList = [];
  final DateTime now = DateTime.now();
  late String startDate;
  late String endDate;
  bool loading = false;

  @override
  void initState() {
    super.initState();
    startDate = Utils.getFormatDate(dateTime: now);
    endDate = Utils.getFormatDate(dateTime: now.add(const Duration(days: 90)));
    getDataList();
  }

  Future getDataList() async {
    try {
      setState(() {
        loading = true;
      });
      final params = JIRIParamsData(
          startDate: startDate,
          endDate: endDate,
          status: widget.status,
          type: widget.type,
          page: page
      );
      final result = await CalendarAPI.chooseAnAuspiciousDay(context, params);
      currentListLength = result?.length ?? 0;
      if (currentListLength < size) {
        _refreshController.loadNoData();
      }
      List<AuspiciousDayItemModel> currList;
      if (page == 1) {
        currList = result ?? [];
      } else {
        currList = [...dataList, ...result??[]];
      }
      setState(() {
        dataList = currList;
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  Future<void> _loadMore() async {
    if (currentListLength == size) {
      page++;
      await getDataList();
      _refreshController.loadComplete();
    } else {
      _refreshController.loadNoData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonHeader.appBar(context: context),
      backgroundColor: ColorStyle.pageDefaultColor,
      // body: Stack(
      //   children: [
      //     Padding(
      //       padding: EdgeInsets.fromLTRB(Constant.PAGEPADDING.w, 20.w, Constant.PAGEPADDING.w, 380.w),
      //       child: CommonListWidget(
      //         controller: _refreshController,
      //         enablePullDown: false,
      //         enablePullUp: true,
      //         onLoading: _loadMore,
      //         header: CustomFreshHeader(refreshController: _refreshController),
      //         child: ListView.builder(
      //           physics: const AlwaysScrollableScrollPhysics(),
      //           itemCount: dataList.length + 1,
      //           itemBuilder: (BuildContext context, int index) {
      //             if (index == 0) {
      //               return const CommonTitleWidget(txt: '宜搬新房');
      //             } else {
      //               final item = dataList[index - 1];
      //               final year = item.date != null ? '${item.date!.split('年')[0]}年' : '';
      //               final day = item.date != null ? item.date!.split(' ')[0].split('年')[1] : '';
      //               final week = item.date != null ? item.date!.split(' ')[1] : '';
      //               final lunarDateStrList = item.lunarDate?.split(' ') ?? [];
      //               final lunarDate1 = lunarDateStrList.removeAt(0);
      //               final lunarDate2 = lunarDateStrList.join(' ');
      //               return GestureDetector(
      //                 onTap: () {
      //                   context.push('/good_day_calendar');
      //                 },
      //                 child: Container(
      //                   key: ValueKey(item.date),
      //                   margin: EdgeInsets.only(top: 20.w),
      //                   padding: EdgeInsets.symmetric(vertical: 40.w),
      //                   decoration: BoxDecoration(
      //                       color: ColorStyle.themeLightColor,
      //                       border: Border.all(width: 5.w, color: ColorStyle.borderColor),
      //                       borderRadius: BorderRadius.all(Radius.circular(60.w))
      //                   ),
      //                   child: IntrinsicHeight(
      //                     child: Row(
      //                       children: [
      //                         Container(
      //                           width: 193.w,
      //                           decoration: BoxDecoration(
      //                               border: Border(right: BorderSide(width: 1.w, color: ColorStyle.borderColor))
      //                           ),
      //                           child: Column(
      //                             mainAxisAlignment: MainAxisAlignment.center,
      //                             children: [
      //                               // '10月23日'
      //                               CommonText(txt: year),
      //                               CommonText(txt:  day, weight: FontWeight.bold),
      //                               CommonText(txt: week),
      //                             ],
      //                           ),
      //                         ),
      //                         Expanded(child: Padding(
      //                           padding: EdgeInsets.symmetric(horizontal: 20.w),
      //                           child: Row(
      //                             children: [
      //                               Expanded(child: Column(
      //                                 crossAxisAlignment: CrossAxisAlignment.start,
      //                                 children: [
      //                                   CommonText(txt: lunarDate1, weight: FontWeight.bold),
      //                                   CommonText(txt: lunarDate2, weight: FontWeight.bold),
      //                                   CommonText(txt: item.jishenyiqu??''),
      //                                 ],
      //                               )),
      //                               Image.asset('assets/icons/icon_arrow_right.png', width: 10.w,)
      //                             ],
      //                           ),
      //                         ))
      //                       ],
      //                     ),
      //                   ),
      //                 ),
      //               );
      //             }
      //           },
      //         ),
      //       ),
      //     ),
      //     Positioned(
      //       bottom: 0,
      //       left: 0,
      //       right: 0,
      //       child: Container(
      //         padding: EdgeInsets.symmetric(horizontal: 40.w),
      //         decoration: BoxDecoration(
      //           color: ColorStyle.themeLightColor,
      //           borderRadius: BorderRadius.only(
      //             topLeft: Radius.circular(60.w),
      //             topRight: Radius.circular(60.w)
      //           ),
      //           boxShadow: [
      //             BoxShadow(
      //               color: Colors.black.withOpacity(0.3),
      //               offset: const Offset(0, -2),
      //               blurRadius: 10,
      //               spreadRadius: 0,
      //             ),
      //           ]
      //         ),
      //         child: SafeArea(
      //           child: SizedBox(
      //             height: 330.w,
      //             child: Column(
      //               children: [
      //                 Container(
      //                   width: double.infinity,
      //                   height: 110.w,
      //                   alignment: Alignment.centerLeft,
      //                   decoration: BoxDecoration(
      //                     border: Border(bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor))
      //                   ),
      //                   child: const CommonText(txt: '查询日期范围'),
      //                 ),
      //                 Expanded(child: Padding(
      //                   padding: EdgeInsets.symmetric(vertical: 40.w),
      //                   child: Row(
      //                     mainAxisAlignment: MainAxisAlignment.spaceBetween,
      //                     children: [
      //                       Column(
      //                         mainAxisAlignment: MainAxisAlignment.spaceBetween,
      //                         children: [
      //                           Text('开始日期', style: TextStyle(fontSize: 30.sp, color: ColorStyle.red)),
      //                           CommonText(txt: DatePickerUtil.dateConversionLunar(DateTime.parse(startDate))),
      //                           CommonText(txt: Utils.getFormatDate(dateTime: DateTime.parse(startDate), format: 'YYYY年MM月DD日')),
      //                         ],
      //                       ),
      //                       Image.asset('assets/icons/icon_arrow_big.png', width: 86.w),
      //                       Column(
      //                         mainAxisAlignment: MainAxisAlignment.spaceBetween,
      //                         children: [
      //                           Text('结束日期', style: TextStyle(fontSize: 30.sp, color: ColorStyle.red)),
      //                           CommonText(txt: DatePickerUtil.dateConversionLunar(DateTime.parse(endDate))),
      //                           CommonText(txt: Utils.getFormatDate(dateTime: DateTime.parse(endDate), format: 'YYYY年MM月DD日')),
      //                         ],
      //                       ),
      //                     ],
      //                   ),
      //                 ))
      //               ],
      //             ),
      //           ),
      //         ),
      //       ),
      //     )
      //   ],
      // ),
      body: CommonListWidget(
        controller: _refreshController,
        enablePullDown: false,
        enablePullUp: true,
        onLoading: _loadMore,
        header: CustomFreshHeader(refreshController: _refreshController),
        child: (loading && dataList.isEmpty)
          ? const Center(child: CommonLoadingCircleWidget())
          : (
            dataList.isNotEmpty
              ? ListView.builder(
                  physics: const AlwaysScrollableScrollPhysics(),
                  padding: EdgeInsets.fromLTRB(Constant.PAGEPADDING.w, 20.w, Constant.PAGEPADDING.w, 0),
                  itemCount: dataList.length + 1,
                  itemBuilder: (BuildContext context, int index) {
                    if (index == 0) {
                      return CommonTitleWidget(txt: '${widget.status == 'y' ? '宜' : '忌'}${widget.type}');
                    } else {
                      final item = dataList[index - 1];
                      final year = item.date != null ? '${item.date!.split('年')[0]}年' : '';
                      final day = item.date != null ? item.date!.split(' ')[0].split('年')[1] : '';
                      final week = item.date != null ? item.date!.split(' ')[1] : '';
                      final lunarDateStrList = item.lunarDate?.split(' ') ?? [];
                      final lunarDate1 = lunarDateStrList.removeAt(0);
                      final lunarDate2 = lunarDateStrList.join(' ');
                      return GestureDetector(
                        onTap: () {
                          context.push('/good_day_calendar');
                        },
                        child: Container(
                          key: ValueKey(item.date),
                          margin: EdgeInsets.only(top: 20.w),
                          padding: EdgeInsets.symmetric(vertical: 40.w),
                          decoration: BoxDecoration(
                              color: ColorStyle.themeLightColor,
                              border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                              borderRadius: BorderRadius.all(Radius.circular(60.w))
                          ),
                          child: IntrinsicHeight(
                            child: Row(
                              children: [
                                Container(
                                  width: 193.w,
                                  decoration: BoxDecoration(
                                      border: Border(right: BorderSide(width: 1.w, color: ColorStyle.borderColor))
                                  ),
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      // '10月23日'
                                      CommonText(txt: year),
                                      CommonText(txt:  day, weight: FontWeight.bold),
                                      CommonText(txt: week),
                                    ],
                                  ),
                                ),
                                Expanded(child: Padding(
                                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                                  child: Row(
                                    children: [
                                      Expanded(child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          CommonText(txt: lunarDate1, weight: FontWeight.bold),
                                          CommonText(txt: lunarDate2, weight: FontWeight.bold),
                                          CommonText(txt: item.jishenyiqu??''),
                                        ],
                                      )),
                                      Image.asset('assets/icons/icon_arrow_right.png', width: 10.w,)
                                    ],
                                  ),
                                ))
                              ],
                            ),
                          ),
                        ),
                      );
                    }
                  },
                )
              : Column(
              children: [
                CommonTitleWidget(txt: '宜${widget.type}'),
                const Expanded(child: Center(child: CommonText(txt: '暂无数据')))
              ],
            )
        )
      ),
    );
  }
}
